# Use the official Node.js 22 image for the production stage
FROM node:lts-bullseye AS base
# Set the working directory
WORKDIR /app
ENV LANG=en_US.UTF-8
ENV LC_CTYPE=en_US.UTF-8
#Install necessary packages
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list && \
    sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list && \
    apt-get update
RUN apt-get install -y libc6-dev
RUN npm config set registry https://registry.npmmirror.com/
RUN npm i -g node-gyp

COPY package.json ./
RUN npm install

################
#    Build     #
################
# Step 2 - rebuild the app
FROM base AS builder
WORKDIR /app
COPY . .

# Prisma
RUN npx prisma generate  --schema prisma/schema.prisma
RUN npm run build

################
#    Runner    #
################
# Step 3 - copy all the files and run server
FROM base AS runner
WORKDIR /app
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Set the correct permission for prerender cache
RUN mkdir .next && chown nextjs:nodejs .next
# Automatically leverage output traces to reduce image size
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/node_modules ./node_modules


USER nextjs

ENV NEXT_TELEMETRY_DISABLED=1
ENV DISABLE_PRISMA_TELEMETRY=true
ENV NODE_ENV=production
ENV HOSTNAME="0.0.0.0"
ENV PORT=3000

EXPOSE 3000

CMD ["node", "server.js"]
